package utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import entity.CommonParam;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @version V1.0
 * @Title: 通用工具类
 * @Package
 * @Description:
 * @author: GaleBlade
 * @date:
 */
public class CommonUtils {

    private static AESUtils aesUtils = new AESUtils();
    private static PropertiesUtils settings = new PropertiesUtils("SETTINGS.properties");

    public static int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
    public static int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
    public static Color color = new Color(Integer.parseInt(settings.get("font.r")),Integer.parseInt(settings.get("font.g")),Integer.parseInt(settings.get("font.b")));
    public static Color inputColor = new Color(89,89,89);
    public static Color bgColor = new Color(67,67,67);

    /**
     * 获取文件夹下所有文件的名称 + 模糊查询（当不需要模糊查询时，queryStr传空或null即可）
     * 1.当路径不存在时，map返回retType值为1
     * 2.当路径为文件路径时，map返回retType值为2，文件名fileName值为文件名
     * 3.当路径下有文件夹时，map返回retType值为3，文件名列表fileNameList，文件夹名列表folderNameList
     *
     * @param folderPath 路径
     * @param queryStr   模糊查询字符串
     * @return
     */
    public static List<String> getFilesName(String folderPath, String queryStr) {
        List<String> fileNameList = new ArrayList<String>();//文件名列表
        File f = new File(folderPath);
        fileNameList(f, queryStr, fileNameList);
        return fileNameList;
    }

    /**
     * 递归获取匹配的文件列表
     *
     * @param f
     * @param queryStr
     * @param fileNameList
     */
    public static void fileNameList(File f, String queryStr, List<String> fileNameList) {
        File[] fa = f.listFiles();
        queryStr = queryStr == null ? "" : queryStr;//若queryStr传入为null,则替换为空（indexOf匹配值不能为null）
        assert fa != null;
        for (File fs : fa) {
            if (fs.isDirectory()) {
                if (fs.getName().contains(queryStr)) {
                    fileNameList.add(fs.getAbsolutePath().split("_")[fs.getAbsolutePath().split("_").length-1]);
                }
            }
        }
    }

    public static String getIP() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        System.out.println("Local HostAddress: "+addr.getHostAddress());
        return addr.getHostName();
    }

    /**
     * 加载字体
     */
    public static Font loadFont(String fontFileName, float fontSize) {
        try {
            File file = new File(fontFileName);
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
            aixing.close();
//            GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(dynamicFontPt);
            return dynamicFontPt;
        } catch(Exception e) {
            e.printStackTrace();
            return new Font("等线", Font.PLAIN, 14);
        }
    }

//    public static Font getFont(){
//        PropertiesUtils settings = new PropertiesUtils("SETTINGS.properties");
//        return loadFont("resources/font/" + settings.get("font.name") + ".ttf", Float.parseFloat(settings.get("font.size")));
//    }

    public static Font getFont(){
        return new Font("微软雅黑", Font.PLAIN, 16);
    }

    /**
     * 获取随机数
     *
     * @param num
     * @return
     */
    public static String getRandom(int num) {
        String s = "123456789";
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < num; i++) {
            char c = s.charAt(new Random().nextInt(s.length()));
            stringBuilder.append(c);
        }
        return stringBuilder.toString();
    }

    public static String formatJSON(String jsonString){
        if (CommonUtils.getJSONType(jsonString)){
            if (jsonString.startsWith("[") && jsonString.endsWith("]")){
                JSONArray object = JSONObject.parseArray(jsonString);
                return JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
            }else {
                JSONObject object = JSONObject.parseObject(jsonString);
                return JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
            }
        }else {
            return jsonString;
        }
    }

    public static boolean getJSONType(String str) {
        boolean result = false;
        if (StringUtils.isNotBlank(str)) {
            str = str.trim();
            if (str.startsWith("{") && str.endsWith("}")) {
                result = true;
            } else if (str.startsWith("[") && str.endsWith("]")) {
                result = true;
            }
        }
        return result;
    }

    public static String getBody(String cache, ArrayList<CommonParam> secretsList, ArrayList<CommonParam> templateList) throws Exception {
        String dataSecret = secretsList.get(0).getValue();
        String dataSecretIV = secretsList.get(1).getValue();
        String appSecret = secretsList.get(2).getValue();
        JSONObject jsonObject = new JSONObject();
        String data;
        if (!dataSecret.equals("") && !dataSecretIV.equals("") && !appSecret.equals("")){
            data = aesUtils.Encrypt(dataSecret, dataSecretIV, cache);
        }else {
            data = cache;
        }
//        jsonObject.put("data", data);
        for (CommonParam param : templateList){
            if (!param.getKey().toLowerCase().equals("data")){
                if (param.getKey().toLowerCase().equals("timestamp")){
                    String timestamp = System.currentTimeMillis() + "";
                    jsonObject.put(param.getKey(), timestamp);
                }else if (param.getKey().toLowerCase().contains("seq")){
                    String seq;
                    if (param.getValue().contains("+")){
                        seq = getNowTime("yyyyMMddHHmmss") + param.getValue().split(" \\+ ")[1];
                    }else {
                        seq = param.getValue();
                    }
                    jsonObject.put(param.getKey(), seq);
                }else if (param.getKey().toLowerCase().contains("sig")){
                    jsonObject.put(param.getKey(), "");
                }else {
                    jsonObject.put(param.getKey(), param.getValue());
                }
            }else {
                jsonObject.put(param.getKey(), data);
            }
        }
        for (CommonParam param : templateList){
            if (param.getKey().toLowerCase().contains("sig")){
                StringBuilder signParam = new StringBuilder();
                if (param.getValue().contains("+")){
                    for (int i=0;i<param.getValue().split(" \\+ ").length;i++){
                        signParam.append(jsonObject.getString(param.getValue().split(" \\+ ")[i]));
                        System.out.println(jsonObject.getString(param.getValue().split(" \\+ ")[i]) + " + ");
                    }
                }else {
                    if (!param.getValue().equals("")){
                        signParam = new StringBuilder(jsonObject.getString(param.getValue()));
                    }
                }
                String sign = HMacMD5Utils.getHmacMd5Str(appSecret, signParam.toString());
                jsonObject.put(param.getKey(), sign);
            }
        }
//        if (CommonUtils.checkToken()){
//            jsonObject.put("token", caches.get("token"));
//        }else {
//            jsonObject.put("token", getToken());
//        }
//        jsonObject.put("token", "");
        return jsonObject.toString();
    }

    /**
     * 获取当前时间
     *
     */
    public static String getNowTime(String str) {
        SimpleDateFormat df = new SimpleDateFormat(str);//设置日期格式
        return df.format(new Date());
    }

    public static String buildPostParam(ArrayList<CommonParam> dataList){
        StringBuilder result = new StringBuilder("{");
        for (CommonParam data : dataList){
            result.append("\"").append(data.getKey()).append("\":\"").append(data.getValue()).append("\",");
        }
        result.deleteCharAt(result.length()-1).append("}");
        return result.toString();
    }

    public static String buildGetParam(ArrayList<CommonParam> dataList){
        StringBuilder result = new StringBuilder("?");
        for (CommonParam data : dataList){
            if (!data.getKey().equals("")){
                result.append(data.getKey()).append("=").append(data.getValue()).append("&");
            }
        }
            result.deleteCharAt(result.length()-1);
        return result.toString();
    }

    public static String formartHTML(String html){
        if(StringUtils.isNotBlank(html)) {
            try {
                Document doc = Jsoup.parseBodyFragment(html);
                html = doc.outerHtml();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return html;
    }

}
